<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="userInfo.names" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.trim="userInfo.ages" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="userInfo.sexs">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button type="button" @click="add" class="btn btn-primary">添加/修改</button>
    </div>
    <div>
      <table class="table" border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in arr" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.names }}</td>
          <td>{{ item.ages }}</td>
          <td>{{ item.sexs }}</td>
          <td>
            <button type="button" @click="remove(item.id)" class="btn btn-light">删除</button>
            <button type="button" @click="redact(item)" class="btn btn-light">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        { id: 1, names: 'Tom', ages: 19, sexs: '男' },
        { id: 2, names: 'Jone', ages: 21, sexs: '女' }
      ],
      userInfo: {
        id: 0,
        names: '',
        ages: '',
        sexs: ''
      }
    }
  },
  methods: {
    add() {
      var ids = this.arr.find(item => item.id === this.userInfo.id)
      this.userInfo.id = this.arr.length > 0 ? this.arr[this.arr.length - 1].id + 1 : 1
      if (this.userInfo.names == '' || this.userInfo.ages == '' || this.userInfo.sexs == '') return alert('请输入内容')
      if (!ids) {
        this.arr.push(this.userInfo)
      } else {
        var index = this.arr.findIndex(obj => obj.id === ids.id)
        const vid = ids.id
        for (var k in this.userInfo) {
          this.arr[index][k] = this.userInfo[k]
        }
        this.arr[index].id = vid
      }
      this.userInfo = {
        id: 0,
        names: '',
        ages: '',
        sexs: ''
      }
    },
    remove(id) {
      this.arr.splice(
        this.arr.findIndex(obj => obj.id === id),
        1
      )
      this.userInfo = {
        id: 0,
        names: '',
        ages: '',
        sexs: ''
      }
    },
    redact(value) {
      for (var k in value) {
        this.userInfo[k] = value[k]
      }
    }
  }
}
</script>
